import { type } from './utils'

const loading = new Map()

export function loadSource(nodeName, name, source, attrs, doc = document) {
    if (!doc.head) {
        doc.body.insertAdjacentHTML('beforebegin', '<head></head>')
    }
    return new Promise((resolve, reject) => {
        const em = `${nodeName}: ${source} 加载失败`
        if (loading.has(source)) {
            const el = loading.get(source)
            el.addEventListener('load', function() {
                resolve()
            })
            el.addEventListener('error', function() {
                reject(new URIError(em))
            })
        } else if (doc.querySelector(`${nodeName}[${name}="${source}"]`)) {
            resolve()
        } else {
            const el = document.createElement('script')
            el.setAttribute(name, source)
            if (type(attrs) === 'object') {
                Object.entries(attrs).forEach(([k, v]) => {
                    el.setAttribute(k, v)
                })
            }
            el.addEventListener('load', function() {
                loading.delete(source)
                resolve()
            })
            el.addEventListener('error', function() {
                loading.delete(source)
                doc.head.removeChild(el)
                reject(new URIError(em))
            })
            doc.head.append(el)
            loading.set(source, el)
        }
    })
}